package core

import (
	"github.com/robfig/cron/v3"
	"sort"
	"sync"
	"sync/atomic"
)

// LoadBalance
// @Description: 负载均衡
type LoadBalance struct {
	Servers        ServerSlice  `json:"servers"` //集群服务列表
	totalWeight    int64        //总权重
	instanceRWLock sync.RWMutex //实例读写锁
	task           *cron.Cron   //任务调度
	key            string       //服务对应注册表的key
}

// LoadLoop
//
//	@Description: 负载轮训
//	@receiver this
func (this *LoadBalance) loadLoop() *server {
	this.instanceRWLock.RLock()
	defer this.instanceRWLock.RUnlock()
	//如果无实例则退出轮训
	if this == nil || this.Servers.Len() == 0 {
		return nil
	}
	for _, s := range this.Servers {
		atomic.AddInt64(&s.currentWeight, s.Weight-s.FailureWeight)
	}
	//进行排序
	sort.Sort(this.Servers)
	//获取最大权重服务
	maxWeightServer := this.Servers[0]
	atomic.AddInt64(&maxWeightServer.currentWeight, -this.totalWeight)
	return maxWeightServer
}

// SumWeight
//
//	@Description: 计算总权重
//	@receiver this
func (this *LoadBalance) sumWeight() {
	var totalWeight = int64(0)
	for _, s := range this.Servers {
		s.currentWeight = 0
		totalWeight += s.Weight - s.FailureWeight
	}
	this.totalWeight = totalWeight
}
